package server

import (
	"StudentMicroService/protos"
	"errors"
	"fmt"
	"golang.org/x/net/context"
)

var _students = make(map[int32]protos.Student)

type StudentService struct {
}

func (*StudentService) Add(ctx context.Context, req *protos.AddRequest) (*protos.AddResponse, error) {
	var maxKey int32 = 0
	for k, _ := range _students {
		if k > maxKey {
			maxKey = k
		}
	}
	maxKey++
	req.Student.Id = maxKey
	_students[maxKey] = *req.Student

	return &protos.AddResponse{IsSuccess: true, Id: maxKey, Message: ""}, nil
}
func (*StudentService) Update(ctx context.Context, req *protos.UpdateRequest) (*protos.UpdateResponse, error) {
	if _, ok := _students[req.Student.Id]; ok {
		_students[req.Student.Id] = *req.Student
		return &protos.UpdateResponse{IsSuccess: true, Message: ""}, nil
	} else {
		msg := fmt.Sprintf("No student of id [%v]", req.Student.Id)
		return &protos.UpdateResponse{IsSuccess: false, Message: msg}, errors.New(msg)
	}
}
func (*StudentService) Delete(ctx context.Context, req *protos.DeleteRequest) (*protos.DeleteResponse, error) {
	delete(_students, req.Id)
	return &protos.DeleteResponse{IsSuccess: true}, nil
}
func (*StudentService) ListAll(ctx context.Context, req *protos.ListAllRequest) (*protos.ListAllResponse, error) {
	resp := &protos.ListAllResponse{}
	resp.Count = int32(len(_students))

	stu := make([]*protos.Student, resp.Count)
	var i int32 = 0
	for k, _ := range _students {
		s := _students[k]
		stu[i] = &s
		i++
	}
	resp.Students = stu
	return resp, nil
}
func (*StudentService) FindOne(ctx context.Context, req *protos.FindOneRequest) (*protos.FindOneResponse, error) {
	if s, ok := _students[req.Id]; ok {
		return &protos.FindOneResponse{Student: &s}, nil
	} else {
		return &protos.FindOneResponse{Student: nil}, errors.New(fmt.Sprintf("No student of id [%v]", req.Id))
	}
}
